﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;
using System.IO.Ports;
namespace ModbusTestTool
{
    public partial class settings : Form
    {

        MainWindow m_parent;
        public settings(MainWindow parent)
        {
            InitializeComponent();
            state currentstate = parent.ReadCurrentState();

            // This code gets the data for the description internally sets the current port to the value storedin comports.
            List<COMPortInfo> comInfo = new List<COMPortInfo>();
            comInfo = COMPortInfo.GetCOMPortsInfo();

            string[] comports = SerialPort.GetPortNames();
            string[] comport_plus_desc = new string[comInfo.Count];

            for (int i=0; i < comInfo.Count; i++)
            {
                comport_plus_desc[i] = comInfo[i].Name + " " + comInfo[i].Description;
                
            }
            
            


            //comboBox1.DataSource = SerialPort.GetPortNames();

            comboBox1.DataSource = comport_plus_desc;
            
            textBox1.Text = currentstate.modbusId.ToString();
            textBox2.Text = currentstate.baudSpeed.ToString();
            m_parent = parent;

            //int index = Array.IndexOf(SerialPort.GetPortNames(), currentstate.comPort);

            int index = findIndex(currentstate.comPort, comport_plus_desc);
            
            if (index != -1)
            {
                comboBox1.SelectedIndex = index; 
            }

            this.FormClosing += new FormClosingEventHandler(settings_FormClosing);
        }

        int findIndex(string item,String [] list)
        {
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i].Contains(item))
                    return i;
            }
            return -1;
        
        }

        void settings_FormClosing(object sender, FormClosingEventArgs e)
        {
            saveState();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            
            saveState();
        }

        private void saveState()
        {
            

            m_parent.setCurrentState((((string) comboBox1.SelectedValue).Split(' '))[0],byte.Parse(textBox1.Text),int.Parse(textBox2.Text));
        }
    }
}
